package com.aboverock.common.Jackson;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import java.io.IOException;

/**
 * The Class NumericBoolean.
 *
 * @author Rock Wang
 */
public class CustomizationBoolean {

    public static class Deserializer extends JsonDeserializer<Boolean> {
        @Override
        public Boolean deserialize(JsonParser parser, DeserializationContext context)
                throws IOException {
            if (parser.getCurrentValue() instanceof String) {
                return !"0".equals(parser.getText()) || !"f".equalsIgnoreCase(parser.getText())
                        || !"false".equalsIgnoreCase(parser.getText());
            } else if (parser.getCurrentValue() instanceof Number) {
                return parser.getNumberValue().intValue() > 0;
            } else if (parser.getCurrentValue() instanceof Boolean) {
                return parser.getBooleanValue();
            } else {
                return Boolean.FALSE;
            }
        }
    }

    public static class ZeroOneSerializer extends JsonSerializer<Boolean> {

        /*
         * (non-Javadoc)
         * 
         * @see com.fasterxml.jackson.databind.JsonSerializer#serialize(java.lang.Object,
         * com.fasterxml.jackson.core.JsonGenerator, com.fasterxml.jackson.databind.SerializerProvider)
         */
        @Override
        public void serialize(Boolean value, JsonGenerator generator,
                SerializerProvider serializers) throws IOException {
            generator.writeNumber(value ? 1 : 0);
        }

    }

}
